package setting

import (
	"context"
	"fmt"
	"github.com/spf13/cast"
	"onvif_server/internal/model"
	"onvif_server/internal/repository"
	"reflect"
	"sync"
	"time"
)

type ValueType interface {
	int | string | bool
}

var settings = &sync.Map{}
var settingRepo repository.SettingRepository

func Init(repo repository.SettingRepository) {
	settingRepo = repo
	refresh()
}

func refresh() {
	ms, err := settingRepo.GetAll(context.Background())
	if err != nil {
		return
	}
	for i := range ms {
		settings.Store(ms[i].Key, ms[i])
	}
}

func Set(key string, val any) error {
	_m, ok := settings.Load(key)
	if !ok {
		return nil
	}
	m := _m.(*model.Setting)
	vT := reflect.TypeOf(val).String()
	if m.Type == "" {
		m.Type = vT
	} else {
		if vT != m.Type {
			return ErrorType
		}
	}
	v, err := toValue(val)
	if err != nil {
		return err
	}
	m.Val = v
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
	defer cancel()
	if err = settingRepo.Update(ctx, m); err != nil {
		return err
	}
	return nil
}

func Get(key string) any {
	val, ok := settings.Load(key)
	if !ok {
		return nil
	}
	fmt.Println(val)
	return val.(*model.Setting).Val
}
func GetBool(key string) bool {
	return cast.ToBool(Get(key))
}
func GetInt(key string) int {
	return cast.ToInt(Get(key))
}
func GetString(key string) string {
	return cast.ToString(Get(key))
}
func GetSliceInt(key string) []int {
	return []int{}
}
func GetSliceString(key string) []string {
	return []string{}
}
